var player = null;
var distinctedFields = new Array();

function playTrack($tr)
{
	$('.played').removeClass('played');
	$tr.addClass('played');
	var filename = trim($tr.find('.column_file_uri').text());
	player.SetVariable("player:jsUrl", filename);
	player.SetVariable("player:jsPlay", "");
	$tr
		.find('.column_filename a img')
		.attr('src', 'http://localhost/projets/kasifimusicmanager/core/lib/famfamfam_silk_icons_v013/icons/control_pause.png')
		.parent()
		.removeAttr('onclick')
		.unbind('click')
		.click(function(){return pauseTrack($tr);});
	return false;
}

function pauseTrack($tr)
{
	player.SetVariable("player:jsPause", "");
	$tr
		.find('.column_filename a img')
		.attr('src', 'http://localhost/projets/kasifimusicmanager/core/lib/famfamfam_silk_icons_v013/icons/control_play.png')
		.parent()
		.removeAttr('onclick')
		.unbind('click')
		.click(function(){return playTrack($tr);});
	return false;
}

function load_music_subdir(listingName, subdir)
{
	listingParameters[listingName]['subdir'] =  subdir;
	return updateTable(listingName, true);
}

function refreshSteps()
{
	$.ajax({
		type: "GET",
				url: core_uri+'/action.php',
				data: 'do=refreshSteps&step='+currentStepName,
		success: function(html){
			$('ul#steps').empty().append(html);
		}
	});
	return false;
}

function moveToTheNextStep($tr)
{
//get line id
var line = null;
var classes = $tr.attr('class').split(' ');
for (var classeIndex in classes)
	if (classes[classeIndex].indexOf('line_') === 0)
		line = classes[classeIndex].substr(5);

	$.ajax({
		type: "GET",
				url: core_uri+'/action.php',
				data: 'do=moveFileToTheNextStep&step='+currentStepName+'&file='+line+'&currentStepName='+currentStepName,
		success: function(msg){
			if(msg == 'done')
			{
				$tr.remove();
				rewrite_tr_alternate_class($tr.parent().parent());
				refreshSteps();
			}
			else alert("TECHNICAL ERROR ! " + msg);
		}
	});
}

function getGraphURI(){
	return 'http://chart.apis.google.com/chart?'
			+'chxt=x,y'
			+'&chxl='
			+'0:|'
			+'0|'+(biggestDir/2)+'|'+biggestDir+'|'
			+'1:|'
			+'Cleaned|Image Added|Lyrics Added|Bpm Added|Normalized|Undoubled|Retagged|Selected|Downloaded'
			+'&cht=bhs'
			+'&chd=t:'+(100*downloadedCount/biggestDir)+','+(100*selectedCount/biggestDir)+','+(100*retaggedCount/biggestDir)+','+(100*undoubledCount/biggestDir)+','+(100*normalizedCount/biggestDir)+','+(100*bpm_addedCount/biggestDir)+','+(100*lyrics_addedCount/biggestDir)+','+(100*image_addedCount/biggestDir)+','+(100*cleanedCount/biggestDir)
			+'&chco=dddddd'
			+'&chls=2.0'
			+'&chs=600x110'
			+'&chbh=6';
}

function initListingEvents(){
/*
	//doubleclick play the track by double click on the line
	$('table.listing tbody tr)')
		.unbind('dblclick').dblclick(function(){
			//playTrack(trim($(this).find('.column_file_uri').text());
		});*/
	
	//when a field is edited : add autocomplete when first edit of line + manage visual effects for editing
	$('table.listing input.id3_field').unbind('focus').focus(function(){
		var $this = $(this);
		var tag = $this.attr('name');
		$this.parent().parent().parent().addClass('edited');
		$this.attr('title', $this.val());
		$this.addClass('edited').addClass('not_saved');
		if ($this.is(':not(.autocompleteAdded)'))
		{
			$this.autocomplete(distinctedFields[tag], {
				minChars: 0,
				autoFill: false,
				mustMatch: false,
				matchContains: true,
				scrollHeight: 400
			});
		}
		$this.addClass('autocompleteAdded');
	});
	
	
	//when a field is blur : save the ID3 Tag + manage visual effects for stoping editing
	$('table.listing input.id3_field').unbind('blur').blur(function(){
		var $this = $(this);
		if ($this.val() != $this.attr('title'))
		{
		//get column id
		var column = null;
		var classes = $this.parent().parent().attr('class').split(' ');
		for (var classeIndex in classes)
			if (classes[classeIndex].indexOf('tag_') === 0)
				column = classes[classeIndex].substr(4);
		
		//get line id
		var line = null;
		var classes = $this.parent().parent().parent().attr('class').split(' ');
		for (var classeIndex in classes)
			if (classes[classeIndex].indexOf('line_') === 0)
				line = classes[classeIndex].substr(5);
		
			$.ajax({
				type: "GET",
				url: core_uri+'/action.php',
				data: 'do=updateId3Tag&step='+currentStepName+'&file='+line+'&tag='+column+'&value='+escape($this.val()),
				success: function(msg){
					if(msg == 'done')
					{
						$this.removeClass('not_saved');
						if($this.val().length > 0)
							$this.parent().removeClass('empty_field');
						else
							$this.parent().addClass('empty_field');
					}
					else
					{
						alert("TECHNICAL ERROR ! " + msg);
						$this.val($this.attr('title'));
						$this.removeClass('not_saved');
					}
				}
			 });
		}
		else
		{
			$this.removeClass('not_saved');
		}
		$this.removeClass('edited');
		$this.parent().parent().parent().removeClass('edited');
	});
	
	//create autocomplete lists
	$('table.listing th)').each(function(){
		if (_getClassAttribute('JS_ATTR_', $(this)) === false)
		{
			var tag = _getClassAttribute('JS_ATTR_', $(this));
			distinctedFields[tag] = new Array();
			$('table.listing input.id3_field[name='+tag+'][value!=]').each(function(){
				var value = $(this).val();
				var newValue = true;
				for (val in distinctedFields[tag])
					if(distinctedFields[tag][val] == value)
						newValue = false;
				if (newValue)
				distinctedFields[tag].push(value);
			});
			distinctedFields[tag] = distinctedFields[tag].sort();
		}
	});
	
	//TODO use typewatch to reduce ajax call when type a new filter...
	$('.filter_value').each(function(){
		var $this = $(this);
		$this.typeWatch({
			 callback:function(){
				 filterThisField(getListingName($(this.el)), _getClassAttribute('JS_ATTR_', $this.parent()), $this.val());
			 },
			 wait:750,          // milliseconds
			 highlight:true,     // highlight text on focus
			 enterkey:true,     // allow "Enter" to submit data on INPUTs
			 captureLength:-1
		});
	});
	
	//TODO when check_all_cb is checked and after and cb is unchecked check_all_cb is not unckecked
	$('input.multiple_action').change(function(){
		if($(this).is(':checked'))
			$(this).parent().parent().addClass('selected');
		else
			$(this).parent().parent().removeClass('selected');
	});
	
	player = $('#mp3player').get(0);
	$('#fileTree').fileTree({
		root: rootDir,
		script: core_uri+'/jqueryFileTree.php',
		folderEvent: 'click',
		expandSpeed: 300,
		multiFolder: false,
		collapseSpeed: 300,
		loadMessage: 'Pleas wait...',
		dblClickFolderFunction:function(a) {
			var $a = $(a);
			load_music_subdir(getListingName($a), str_replace(rootDir, '/', $a.attr('rel')));
		}
		}, function(file) { 
		alert(file);
	});
}

$(document).ready(function() { 
	initListingEvents();
});
